package com.xoa.service.workflow.flowtype.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowManageLogMapper;
import com.xoa.dao.workflow.FlowPrivMapper;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowRunLog;
import com.xoa.model.workflow.FlowRunModelPrcs;
import com.xoa.model.workflow.FlowRunModelPrcsCount;
import com.xoa.util.ExcelUtil;
import com.xoa.util.FileUploadUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.model.workflow.FlowRun;
import com.xoa.service.workflow.flowtype.FlowRunService;
import org.springframework.transaction.annotation.Transactional;

import java.io.OutputStream;
import java.util.*;

@Service
public class FlowRunServiceImpl implements FlowRunService{
	@Resource
	private FlowRunMapper flowRunMapper;
	@Resource
	private UsersMapper usersMapper;
	@Resource
	private FlowPrivMapper flowPrivMapper;
	@Autowired
	private FlowManageLogMapper flowManageLogMapper;
	
	@Override
	public int getMaxRunId() {
		String runId=flowRunMapper.getMaxRunId();
		if (StringUtils.checkNull(runId)){
			return 0;
		}else {
			return Integer.parseInt(runId);
		}
	}

	@Override
	public void save(FlowRun flowRun) {
		flowRunMapper.insert(flowRun);
	}

	@Override
	public FlowRun find(Integer runId){
		FlowRun f=flowRunMapper.find(runId);
		if(f!=null && !StringUtils.checkNull(f.getBeginTime())) {
		//	f.setBeginTime(DateFormat.getStrTime(DateFormat.getTime(f.getBeginTime())));(王曰岐注释（小彩蛋）)
			if(f.getBeginTime().indexOf(".0")!=-1){
				f.setBeginTime(f.getBeginTime().substring(0,f.getBeginTime().length()-2));
			}
		}
		return f;
	}

	@Override
	public int update(FlowRun flowRun) {
		int a=flowRunMapper.updateByPrimaryKey(flowRun);
		return  a;
	}

	@Transactional
	@Override
	public int updateTime(Map<String,Object> map){
		int a=flowRunMapper.updateTime(map);
		return a;
	}

	@Transactional
	@Override
	public int updateAttachment(Map<String,Object> map){
		int a=flowRunMapper.updateAttachment(map);
		return a;
	}

	/**
	 *
	 * @param state 范围
	 * @param runId 流水号
	 * @param flowId 流程类型
	 * @param runName 工作名称/文号
	 * @param beginDate 流程发起日期开始时间
	 * @param endDate 流程发起日期结束时间
	 * @param workLevel 优先级
	 * @param status 状态
	 * @param page
	 * @param pageSize
	 * @param useFlag
	 * @param users
	 * @return
	 */
	@Override
	public BaseWrappers queryFlowRun(Integer state, Integer runId, Integer flowId, String runName, String beginDate, String endDate, String workLevel, String status, String userId,
									 Integer page, Integer pageSize, boolean useFlag, Users users, String output, HttpServletResponse response, HttpServletRequest request) {
		String company="xoa"+(String) request.getSession().getAttribute(
				"loginDateSouse");
		BaseWrappers baseWrapper=new BaseWrappers();
		Map<String,Object> map=new HashMap<String,Object> ();
		PageParams pageParams = new PageParams();

			pageParams.setUseFlag(useFlag);
			pageParams.setPage(page);
			pageParams.setPageSize(pageSize);
			//map.put("pageParams",pageParams);
			Integer start = (page - 1) * pageSize;
			map.put("start", (page-1)*pageSize);
			map.put("pageSize", pageSize);

		map.put("runId", runId);
		map.put("flowId", flowId);
		map.put("runName", runName);
		map.put("beginDate", beginDate);
		map.put("endDate", endDate);
		map.put("workLevel", workLevel);
		map.put("state", state);
		map.put("status", status);
		if(!StringUtils.checkNull(userId) && userId.indexOf(",")>0){
			userId=userId.substring(0,userId.length()-1);
		}else {
			userId = users.getUserId();
		}
		map.put("userId", userId);
		map.put("currentUserId", users.getUserId());
		map.put("currentUid", users.getUid());
		List<FlowRunModelPrcs> flowRuns = new ArrayList<FlowRunModelPrcs>();
		try {
			flowRuns=flowRunMapper.queryFlowRunBylimit(map);
			Integer count = flowRunMapper.queryFlowRunCount(map);
			//Integer total = count/pageSize;
			Map<String,Object> paramMap=new HashMap<>();
			for(FlowRunModelPrcs flowRunModelPrcs:flowRuns){
				List<Attachment> list = FileUploadUtil.findAtachment(flowRunModelPrcs.getAttachmentId(), flowRunModelPrcs.getAttachmentName(), company);
				flowRunModelPrcs.setList(list);
				paramMap.put("flowId",flowRunModelPrcs.getFlowId());
				paramMap.put("userId",users.getUid());
				paramMap.put("deptId",users.getDeptId());
				paramMap.put("roleId",users.getUserPriv());
				List<Integer> typeList = flowPrivMapper.selPrivByUser(paramMap);//登录人拥有的权限
				if(typeList.size()==5){//全部
					flowRunModelPrcs.setAll("1");
				}
				if(typeList.contains(1)){//管理
					flowRunModelPrcs.setManage("1");
				}
				if(typeList.contains(2)){//监控
					flowRunModelPrcs.setMonitor("1");
				}
				if(typeList.contains(3)){//查询
					flowRunModelPrcs.setQuery("1");
				}
				if(typeList.contains(4)){//编辑
					flowRunModelPrcs.setEdit("1");
				}
				if(typeList.contains(5)){//点评
					flowRunModelPrcs.setComment("1");
				}
				if(!StringUtils.checkNull(flowRunModelPrcs.getEndTime())){
					flowRunModelPrcs.setStatus("已结束");
				}else{
					flowRunModelPrcs.setStatus("执行中");
				}
			}
			if("1".equals(output)) {//output==1,则进行导出操作
				HSSFWorkbook tableWork = ExcelUtil.makeExcelHead("工作流工作查询", 15);
				String[] secondTitles = {"流水号", "流程类型","工作名称/文号","流程发起人","开始时间","公共附件","状态"};
				HSSFWorkbook excelWork = ExcelUtil.makeSecondHead(tableWork, secondTitles);
				String[] beanProperty = {"runId","flowName","runName","userName","beginTime","attachmentName","status"};
				HSSFWorkbook workbook = ExcelUtil.exportExcelData(excelWork, flowRuns, beanProperty);
				response.setContentType("text/html;charset=UTF-8");
				OutputStream out = response.getOutputStream();

				String filename = "工作流工作查询.xls"; //考虑多语言
				filename = FileUtils.encodeDownloadFilename(filename,
						request.getHeader("user-agent"));
				response.setContentType("application/vnd.ms-excel");
				response.setHeader("content-disposition",
						"attachment;filename=" + filename);
				workbook.write(out);
				out.flush();
				out.close();
			}

			baseWrapper.setFlag(true);
			baseWrapper.setStatus(true);
			baseWrapper.setDatas(flowRuns);
			baseWrapper.setTotal(count);
		}catch (Exception e){
			e.printStackTrace();
			baseWrapper.setFlag(false);
			baseWrapper.setStatus(false);
			baseWrapper.setMsg(e.getMessage());
		}
		return baseWrapper;
	}

	@Override
	public int updateFocusUser(Map<String,Object> map){
		int a = flowRunMapper.updateFocusUser(map);
		return a;
	}
	@Override
	public int updateEnd(Map<String,Object> map){
		int a = flowRunMapper.updateEnd(map);
		return a;
	}

	@Override
	public BaseWrappers queryFlowRunCount(HttpServletRequest request) {
		BaseWrappers baseWrapper=new BaseWrappers();
		Map<String,Object> map=new HashMap<String,Object> ();
		List<FlowRunModelPrcsCount> flowRunModelPrcsCounts=new ArrayList<FlowRunModelPrcsCount>();
		FlowRunModelPrcsCount queryFlowRunPerformCount=flowRunMapper.queryFlowRunPerformCount(map);
		FlowRunModelPrcsCount queryFlowRunEndCount=flowRunMapper.queryFlowRunEndCount(map);
		FlowRunModelPrcsCount queryFlowRunArchiveCount=flowRunMapper.queryFlowRunArchiveCount(map);
		flowRunModelPrcsCounts.add(queryFlowRunPerformCount);
		flowRunModelPrcsCounts.add(queryFlowRunEndCount);
		flowRunModelPrcsCounts.add(queryFlowRunArchiveCount);
		baseWrapper.setFlag(true);
		baseWrapper.setStatus(true);
		baseWrapper.setDatas(flowRunModelPrcsCounts);
		return baseWrapper;
	}

	@Override
	public ToJson<FlowRunLog> selFlowRunLog(Integer page,Integer pageSize,boolean useFlag,String starTime,String endTime,String runId,String flowName,String jobsName,String type,String ProcessingPerson,String ip) {
		ToJson<FlowRunLog> flowRunLogListToJson = new ToJson<FlowRunLog>();
        Map map = new HashMap();
		PageParams pageParams = new PageParams();
		pageParams.setPage(page);
		pageParams.setPageSize(pageSize);
		pageParams.setUseFlag(useFlag);


        Map map1 = new HashMap();

        map.put("pageParams", pageParams);
		if("请选择".equals(flowName)){
			flowName ="";
		}
		map.put("runId",runId);
		map.put("starTime",starTime);
		map.put("endTime",endTime);
		map.put("flowName",flowName);
		map.put("runName",jobsName);
		//如果是全部操作类型
		if("0".equals(type)){
			map.put("type","");
		}else{
			map.put("type",type);
	    }

		map.put("ProcessingPerson",ProcessingPerson);
		map.put("ip",ip);
   //----------------------------
		map1.put("runId",runId);
		map1.put("starTime",starTime);
		map1.put("endTime",endTime);
		map1.put("flowName",flowName);
		map1.put("runName",jobsName);
		//如果是全部操作类型
		if("0".equals(type)){
			map1.put("type","");
		}else{
			map1.put("type",type);
		}
		map1.put("ProcessingPerson",ProcessingPerson);
		map1.put("ip",ip);
		//分页按条件查询数据
		List<FlowRunLog> flowRunLogList = flowRunMapper.selFlowRunLog(map);
		//查询结果总数 lr注释
		//List<FlowRunLog> flowRunLogList1 = flowRunMapper.selFlowRunLog(map1);
		for(FlowRunLog flowRunLog:flowRunLogList){
			flowRunLog.setUserName(usersMapper.getUsernameByUserId(flowRunLog.getUserId()));
			if (flowRunLog.getFlowPrcs()!=null&&flowRunLog.getFlowPrcs()!=0){
				String prcsName=flowManageLogMapper.getPrcsName(flowRunLog.getFlowPrcs().toString(), flowRunLog.getFlowId().toString());
				flowRunLog.setPrcsName(prcsName);
			}
			if (0==flowRunLog.getPrcsId()){
				flowRunLog.setPrcsId(null);
			}
		}
		flowRunLogListToJson.setObj(flowRunLogList);
		flowRunLogListToJson.setTotleNum(pageParams.getTotal());
		flowRunLogListToJson.setFlag(0);
		return  flowRunLogListToJson;
	}

	/**
	 * 流程步骤日志删除
	 * 王禹萌
	 * 2018-07-16 11：02
	 * @param logId 日志 ID
	 * @return
	 */
	@Override
	public ToJson<FlowRunLog> delFlowRunLog(Integer logId) {
		ToJson<FlowRunLog> json =new ToJson<FlowRunLog>(1,"err");
		try {
			int count = flowRunMapper.delFlowRunLog(logId);
			if(count>0){
				json.setMsg("ok");
				json.setFlag(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}
}
